package com.tutu.model.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.tutu.model.bean.UserInfo;
import com.tutu.model.db.UserAccountDB;

/**
 * @author 图图 2020/10/10
 *
 * 用户信息操作类
 */
public class UserAccountDao {

    private  final  UserAccountDB mHelper;

    public UserAccountDao(Context context) {
       mHelper =  new UserAccountDB(context);
    }

    /**
     * 添加一个账号
     * @param user
     */
    public void addAccount(UserInfo user){
        // 1.获取数据库对象
        SQLiteDatabase db = mHelper.getReadableDatabase();

        // 2.执行添加操作
        ContentValues values = new ContentValues();
        values.put(UserAccountTable.COL_HXID,user.getHxid());
        values.put(UserAccountTable.COL_USERNAME,user.getUsername());
        values.put(UserAccountTable.COL_USERPWD,user.getUserpwd());
        values.put(UserAccountTable.COL_NICK,user.getNick());
        values.put(UserAccountTable.COL_PHOTO,user.getPhoto());
        values.put(UserAccountTable.COL_PHONE,user.getPhone());
        values.put(UserAccountTable.COL_EMAIL,user.getEmail());
        values.put(UserAccountTable.COL_GENDER,user.getGender());
        values.put(UserAccountTable.COL_REALNAME,user.getRealname());

        db.replace(UserAccountTable.TAB_NAME,null,values);
    }

    /**
     * 根据环信id查用户
     * @param hxid
     * @return
     */
    public UserInfo getUserByHxid(String hxid){
        // 1.获取数据库对象
        SQLiteDatabase db = mHelper.getReadableDatabase();

        // 2.执行查询语句
        String sql = "select * from " + UserAccountTable.TAB_NAME + " where " + UserAccountTable.COL_HXID + "=?";

        Cursor cursor = db.rawQuery(sql, new String[]{hxid});
        UserInfo userInfo = null;
        if(cursor.moveToNext()){
            userInfo = new UserInfo();
            // 封装数据
            userInfo.setHxid(cursor.getString(cursor.getColumnIndex(UserAccountTable.COL_HXID)));
            userInfo.setUsername(cursor.getString(cursor.getColumnIndex(UserAccountTable.COL_USERNAME)));
            userInfo.setUserpwd(cursor.getString(cursor.getColumnIndex(UserAccountTable.COL_USERPWD)));
            userInfo.setNick(cursor.getString(cursor.getColumnIndex(UserAccountTable.COL_NICK)));
            userInfo.setPhoto(cursor.getString(cursor.getColumnIndex(UserAccountTable.COL_PHOTO)));
            userInfo.setPhone(cursor.getString(cursor.getColumnIndex(UserAccountTable.COL_PHONE)));
            userInfo.setEmail(cursor.getString(cursor.getColumnIndex(UserAccountTable.COL_EMAIL)));
            userInfo.setGender(cursor.getInt(cursor.getColumnIndex(UserAccountTable.COL_GENDER)));
            userInfo.setRealname(cursor.getString(cursor.getColumnIndex(UserAccountTable.COL_REALNAME)));
        }

        // 3.关闭资源
        cursor.close();

        // 4.返回数据
        return  userInfo;
    }
}
